"""
安全管理模块信号处理
"""
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth import get_user_model
from django.utils import timezone
from .models import SecurityAuditLog

User = get_user_model()


@receiver(post_save, sender=User)
def log_user_creation(sender, instance, created, **kwargs):
    """记录用户创建安全日志"""
    if created:
        SecurityAuditLog.objects.create(
            event_type=SecurityAuditLog.EventType.DATA_MODIFICATION,
            event_name='用户创建',
            description=f'新用户 {instance.username} ({instance.real_name}) 被创建',
            user=instance,
            metadata={
                'user_id': str(instance.id),
                'username': instance.username,
                'email': instance.email,
                'role': instance.role,
                'created_by': 'system'
            }
        )